package jw

import (
	"github.com/dgrijalva/jwt-go"
	ding "jwgin/utils/dingding"
	"time"
)

//自定义一个字符串
var jwtkey = []byte("JwCode.cn")

type Claims struct {
	UserId  uint
	Role    uint
	Account string
	jwt.StandardClaims
}

//设置 token
func SetToken(id, role uint, acc string) string {
	expireTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId:  id,
		Role:    role,
		Account: acc,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(),
			Issuer:    "JwCode", // 签名颁发者
			Subject:   "JW",     //签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtkey)
	if err != nil {
		ding.DingErr(err.Error())
		return ""
	}
	return tokenString
}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtkey, nil
	})
	return token, Claims, err
}
